import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import { Form, Card, Table, Input, Divider, Button, message } from 'antd';
import { getLocalStorage } from '../../utils/local_storage';
import SendTmpMsgModal from '../../components/SendTmpMsgModal';
import SetTmpMsgModal from '../../components/SetTmpMsgModal';
import AddGHModal from '../../components/AddGhModal';
import styles from './TemplateMessage.less';

const FormItem = Form.Item;

@connect(({ template_message, loading }) => ({
  template_message,
  loading: loading.models.template_message,
}))
@Form.create()
export default class TemplateMessage extends PureComponent {
  state = {
    setTmpModalVisible: false,
    sendTmpMsgModalVisible: false,
    addGHVisible: false,
    editGHVisible: false,
    accountId: '',
    template_list: [],
    tmpMsg: [],
    appid: '',
  };

  // 加载页面后拉取公众号列表
  componentDidMount() {
    this.props.dispatch({
      type: 'template_message/fetchAccountList',
    });
  }

  // 设置模板消息列表参数
  componentWillReceiveProps() {
    const { tmpList: { template_list } } = this.props.template_message;
    this.setState({
      template_list: template_list,
    });
  }

  // 配置模板处理
  showSetTemplateModal = (id, appid) => {
    // 通过公众号id查询该公众号模板列表
    this.props.dispatch({
      type: 'template_message/fetchTmpList',
      payload: id,
    });
    // 设置配置模板modal可见
    this.setState({
      accountId: id,
      appid: appid,
      setTmpModalVisible: true,
    });
  };
  // 处理模板消息配置成功回调
  handleSetTmpContentOk = () => {
    // 设置modal不可见
    this.setState({
      setTmpModalVisible: false,
    });
    // 判断localstorage是否保存成功
    if (getLocalStorage(this.state.accountId)) {
      message.success('保存成功');
    }
  };
  // 处理模板消息配置取消回调(设置modal不可见)
  handleSetTmpContentCancel = () => {
    this.setState({
      setTmpModalVisible: false,
    });
  };

  // 发送模块处理
  showSendTmpMsgModal = id => {
    // 发送时获取accountid和模板消息内容
    const tmpMsgText = getLocalStorage(id);
    if (tmpMsgText) {
      const tmpMsg = JSON.parse(tmpMsgText);
      this.setState({
        tmpMsg: tmpMsg,
        accountId: id,
        sendTmpMsgModalVisible: true,
      });
    } else {
      message.warning('请先设置模版消息内容');
    }
  };
  // 处理发送模块成功回调
  handleSendTmpMsgOk = v => {
    const { tmpMsg, accountId } = this.state;
    const { send_type, test_openid, send_date } = v;
    this.props.dispatch({
      type: 'template_message/createSchedule',
      payload: {
        accountId: accountId,
        tmpMsg: JSON.stringify(tmpMsg),
        send_type: send_type,
        test_openid: test_openid ? test_openid : '',
        send_date: send_date ? moment(send_date).unix() : '',
      },
    });
    // 设置modal不可见
    this.setState({
      sendTmpMsgModalVisible: false,
    });
  };
  // 处理发送模块取消回调(设置modal不可见)
  handleSendTmpMsgCancel = () => {
    this.setState({
      sendTmpMsgModalVisible: false,
    });
  };

  // 添加公众号
  showAddGHModal = () => {
    this.setState({
      addGHVisible: true,
    });
  };
  // 添加公众号成功回调
  handleAddGHOk = v => {
    const { ghname, ghid, appid, secret } = v;
    this.props.dispatch({
      type: 'template_message/addAccount',
      payload: {
        name: ghname ? ghname : '',
        ghid: ghid,
        appid: appid,
        secret: secret,
      },
    });
    this.setState({
      addGHVisible: false,
    });
  };
  // 添加公众号取消回调(设置modal不可见)
  handleAddGHCancel = () => {
    this.setState({
      addGHVisible: false,
    });
  };

  // 修改公众号
  showEditGHModal = id => {
    this.props.dispatch({
      type: 'template_message/getAccount',
      payload: id,
    });
    this.setState({
      editGHVisible: true,
    });
  };
  // 修改公众号成功回调
  handleEditGHOk = (v, id) => {
    const { ghname, ghid, appid, secret } = v;
    this.props.dispatch({
      type: 'template_message/editAccount',
      payload: {
        id: id,
        name: ghname ? ghname : '',
        ghid: ghid,
        appid: appid,
        secret: secret,
      },
    });
    this.setState({
      editGHVisible: false,
    });
  };
  // 修改公众号取消回调(设置modal不可见)
  handleEditGHCancel = () => {
    this.setState({
      editGHVisible: false,
    });
  };

  // 跳转任务状态页面
  showSchedules = () => {
    this.props.dispatch(
      routerRedux.push({
        pathname: '/schedule',
      })
    );
  };

  // 删除公众号操作
  deleteItem = id => {
    this.props.dispatch({
      type: 'template_message/deleteAccount',
      payload: id,
    });
  };

  // 处理搜索
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        dispatch({
          type: 'template_message/fetchAccount',
          payload: values['search_text'],
        });
      }
    });
  };

  render() {
    const {
      setTmpModalVisible,
      sendTmpMsgModalVisible,
      addGHVisible,
      editGHVisible,
      tmpMsg,
      appid,
      template_list,
      accountId,
    } = this.state;
    const {
      template_message: { accountList, account },
      form: { getFieldDecorator },
      loading,
    } = this.props;

    const btnSet = {
      size: 'small',
      type: 'primary',
    };

    const columns = [
      {
        title: 'Id',
        dataIndex: 'id',
        key: 'id',
      },
      {
        title: '微信账号',
        dataIndex: 'ghid',
        key: 'ghid',
      },
      {
        title: '微信名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: 'AppId',
        dataIndex: 'appid',
        key: 'appid',
      },
      {
        title: '模板消息操作',
        dataIndex: 'tmp_operation',
        key: 'tmp_operation',
        render: (text, record) => (
          <Fragment>
            <Button {...btnSet} onClick={() => this.showSetTemplateModal(record.id, record.appid)}>
              配置模板
            </Button>
            <Divider type="vertical" />
            <Button {...btnSet} onClick={() => this.showSendTmpMsgModal(record.id)}>
              发送
            </Button>
          </Fragment>
        ),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        render: (text, record) => (
          <Fragment>
            <Button size="small" onClick={() => this.showEditGHModal(record.id)}>
              编辑公众号
            </Button>
            <Divider type="vertical" />
            <Button size="small" type="danger" onClick={() => this.deleteItem(record.id)}>
              删除公众号
            </Button>
          </Fragment>
        ),
      },
    ];

    return (
      <div>
        <div>
          <Form className={styles.searchLabel} onSubmit={this.handleSearch} layout="inline">
            <FormItem label="搜索: ">
              {getFieldDecorator('search_text')(
                <Input placeholder="请输入" style={{ width: 300 }} />
              )}
            </FormItem>
            <Button style={{ marginTop: 4 }} type="primary" htmlType="submit">
              查询
            </Button>
          </Form>
          <div className={styles.right_btn}>
            <Button onClick={this.showSchedules} type="primary">
              定时任务列表
            </Button>
            <Button className={styles.addGH} onClick={this.showAddGHModal} type="primary">
              添加公众号
          </Button>
          </div>
        </div>
        <br />
        <Card style={{ marginTop: 40 }} bordered={false}>
          <div>
            <Table
              rowKey="appid"
              loading={loading}
              dataSource={accountList}
              bordered
              columns={columns}
            />
          </div>
        </Card>
        <SetTmpMsgModal
          visible={setTmpModalVisible}
          appid={appid}
          accountId={accountId}
          onOk={this.handleSetTmpContentOk}
          onCancel={this.handleSetTmpContentCancel}
          templateList={template_list}
        />
        <SendTmpMsgModal
          visible={sendTmpMsgModalVisible}
          onOk={this.handleSendTmpMsgOk}
          onCancel={this.handleSendTmpMsgCancel}
          tmpMsg={tmpMsg}
        />
        <AddGHModal
          visible={addGHVisible}
          onOk={this.handleAddGHOk}
          onCancel={this.handleAddGHCancel}
        />
        <AddGHModal
          visible={editGHVisible}
          data={account}
          onOk={this.handleEditGHOk}
          onCancel={this.handleEditGHCancel}
        />
      </div>
    );
  }
}
